<template>
  <div class="follow-edit-ctn">
    <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow :fixed="true" :placeholder="true" @click-left="goBack(true)" />
    <van-form ref="form" @submit="onSumit">
      <div class="formData">
        <van-field v-model="formData.brandName" required :rules="[{ required: true }]" name="brandName" label="品牌" input-align="right" readonly />
        <van-field v-model="formData.showOrgName" required :rules="[{ required: true }]" name="showOrgName" label="展厅" input-align="right" readonly />
        <van-field v-model="formData.name" required :rules="[{ required: true }]" name="name" label="客户姓名" input-align="right" readonly />
        <van-field v-model="formData.sourceChannelName" required :rules="[{ required: true }]" name="sourceChannelName" label="来源渠道" input-align="right" readonly />
        <van-field v-model="formData.interModelName" required :rules="[{ required: true }]" name="interModelName" label="意向车系" input-align="right" readonly />
        <van-field v-model="formData.saleEmp" required :rules="[{ required: true }]" name="saleEmp" label="跟进人员" input-align="right" readonly />
        <van-field readonly clickable required :rules="[{ required: true }]" name="followDate" :value="formData.followDate" label="跟进日期" placeholder="请选择跟进日期" input-align="right" right-icon="arrow" @click="onChooseDate(formData.followDate, 1)" />
        <van-field readonly clickable required :rules="[{ required: true }]" name="cusLevel" :value="formData.cusLevelAlias" label="意向级别" placeholder="请选择意向级别" input-align="right" right-icon="arrow" @click="onPicker(cusLevelColumns, 'cusLevelAlias', 'cusLevel')" />
        <van-field readonly clickable required :rules="[{ required: true }]" name="followType" :value="formData.followTypeName" label="跟进方式" placeholder="请选择跟进方式" input-align="right" right-icon="arrow" @click="onPicker(followTypeList, 'followTypeName', 'followType')" />
        <van-field required name="testDrive" label="是否试驾" input-align="right">
          <template #input>
            <van-radio-group v-model="formData.testDrive" direction="horizontal">
              <van-radio v-for="item in testDriveList" :key="item.value" :name="item.value" icon-size="16px">{{ item.name }}</van-radio>
              <!-- <van-radio name="2" icon-size="16px">否</van-radio> -->
            </van-radio-group>
          </template>
        </van-field>
        <template v-if="formData.cusLevel === 'D'">
          <van-field readonly clickable required :rules="[{ required: true }]" name="dReason" :value="formData.DReasonName" label="D级原因" placeholder="请选择D级原因" input-align="right" right-icon="arrow" @click="onPicker(failReasonColumns, 'DReasonName', 'DReasonId')" />
          <!-- <van-field
            v-model="formData.DFailDes"
            name="DFailDes"
            label="战败他品"
            placeholder="请输入战败他品"
            input-align="right"
          />-->
          <van-field v-model="formData.failReason" name="failReason" label="战败他品" placeholder="请输入战败他品" input-align="right" />
          <van-field v-model="formData.DReasonDes" required :rules="[{ required: true }]" rows="2" autosize name="DReasonDes" label="D级原因说明" type="textarea" placeholder input-align="left" />
        </template>

        <van-field readonly clickable :required="formData.cusLevel !== 'D'" :rules="[{ required: formData.cusLevel !== 'D' }]" name="nextFollowDate" :value="formData.nextFollowDate" label="下次跟进日期" placeholder="请选择下次跟进日期" input-align="right" right-icon="arrow" @click="onChooseDate(formData.nextFollowDate, 2)" />
        <van-field v-model="formData.followNote" required :rules="[{ required: true }]" rows="2" autosize name="followNote" label="跟进情况记录" type="textarea" placeholder input-align="left" />
        <!-- 意向级别选择弹窗 -->
        <van-popup v-model="showPicker" position="bottom">
          <van-picker show-toolbar :columns="columns" @confirm="onPickerConfirm" @cancel="showPicker = false" value-key="name" />
        </van-popup>
        <!-- 日期选择弹窗 -->
        <van-calendar v-model="showCalendar" :default-date="defaultDate" :min-date="minDate" :max-date="maxDate" @confirm="onCalendarConfirm" />
      </div>
      <div class="btn" @click="onSumit('submit')">提交</div>
      <div class="btn saveBtn" @click="onSumit('save')">保存</div>
    </van-form>
  </div>
</template>

<script>
import { parseDate, addDay } from "@/utils/util";
import sellManageApi from "@/api/sellManageApi";
const { secondHandCarFacade, getEnums } = sellManageApi;
export default {
  data() {
    return {
      // 客户信息
      formData1: {
        billId: "单据ID", //单据ID
        brandName: "凯迪拉克", // 品牌
        showOrgName: "厦门集美凯迪拉克", // 展厅
        name: "王某某", // 客户姓名
        sourceChannelName: "垂直媒体-懂车帝", // 来源渠道
        interModelName: "CT5", // 意向车系
        saleEmp: "陈欧某", // 跟进人员
        followDate: "2024-01-05", // 跟进日期
        cusLevel: "A", // 意向级别
        testDrive: "1", // 是否试驾
        DReasonName: "战败客户", // D级原因
        failReason: "A6L", // 战败他品
        // DReasonDes: '说不清楚。地方时间嗯放假了是的福利卡就好搞定了你的给你 集合第三方发的分  分', // D级原因说明
        DReasonDes: "", // D级原因说明
        // nextFollowDate: '2024-01-05', // 下次跟进日期
        nextFollowDate: "", // 下次跟进日期
        // followNote: '根基记录描述根基记录描述根基记录描述根基记录描述根基记录描述根基记录描述根基记录描述', // *跟进情况记录
        followNote: "" // *跟进情况记录
      },
      formData: {
        saleEmp: "",
        followDate: parseDate(new Date(), "-")
      },
      formDataOld: {
        billId: "单据ID", //单据ID
        customerId: "", // 客户档案ID，必填
        brandName: "凯迪拉克", // 所属品牌名称
        brandId: "凯迪拉克", // 所属品牌Id
        showOrgName: "厦门集美凯迪拉克", // 展厅
        name: "王某某", // 客户姓名
        sourceChannelName: "垂直媒体-懂车帝", // 来源渠道
        interModelName: "CT5", // 意向车系名称
        saleEmp: "陈欧某", // 跟进人员
        followPersonId: "", // 跟进人员ID，String，必填
        followDate: "2024-01-05", // 跟进日期 String，必填
        cusLevel: "", // 意向级别,必填，String
        testDrive: "1", // 是否试驾中文
        testDriveAlias: "1", // 是否试驾
        DReasonName: "战败客户", // D级原因
        DReasonId: "", // D级原因，String
        failReason: "A6L", // 战败他品
        // DReasonDes: '说不清楚。地方时间嗯放假了是的福利卡就好搞定了你的给你 集合第三方发的分  分', // D级原因说明
        DReasonDes: "", // D级原因说明
        // DFailDes: '', // 战败原因
        // nextFollowDate: '2024-01-05', // 下次跟进日期
        nextFollowDate: "", // 下次跟进日期
        // followNote: '根基记录描述根基记录描述根基记录描述根基记录描述根基记录描述根基记录描述根基记录描述', // *跟进情况记录
        followNote: "", // *跟进情况记录
        saveOrSubmit: "", // 保存或者提交，必填，String
        orgId: "", // 组织ID,必填
        userId: "" //用户ID，必填，String
      },
      formData3: {
        method: "updateCustomerFollow", // 固定值
        cusViewId: "", // 客户跟进记录ID，必填
        followPersonId: "", // 跟进人员ID，String，必填
        followDate: "", // 跟进日期，String，必填
        cusLevel: "", // 意向级别,必填，String
        DReasonId: "", // D级原因，String
        DReasonDes: "", // D级原因说明
        // DFailDes: '', // 战败原因
        failReason: "", // 战败他品，String
        testDrive: "", // 是否试驾,必填，String
        nextFollowDate: "", // 下次跟进日期,必填，String
        followNote: "", // 跟进情况记录，String
        saveOrSubmit: "" // 保存或者提交，必填，String
      },
      showCalendar: false, // 是否展示日历
      columns: [],
      // 意向级别
      // cusLevelColumns: ['O', 'H', 'A', 'B', 'C', 'D', '未定级'],
      cusLevelColumns: [],
      // 战败原因
      // failReasonColumns: ['打败', '失败', '输了', '没赢'],
      failReasonColumns: [],
      showPicker: false, // 是否展示意向级别选择弹窗
      defaultDate: new Date(),
      currentDateChoose: 0, // 当前进行日期选择的字段，0 没有，1 跟进日期， 2 下次跟进日期
      pickerType: 0, // 1 意向级别选择，2 D级原因选择
      pickerName: "", // 当前使用picker的文本字段
      pickerId: "", // 当前使用picker的ID字段
      // 是否试驾枚举
      testDriveList: [],
      // 跟进方式枚举
      followTypeList: [],
      currentMaxDate: undefined
    };
  },
  computed: {
    maxDate() {
      const test =
        this.currentDateChoose === 2 && this.currentMaxDate
          ? addDay(this.currentMaxDate, new Date())
          : addDay(365, new Date());
      return test;
    },
    minDate() {
      const test =
        this.currentDateChoose === 2
          ? new Date(this.formData.followDate.replaceAll("-", "/"))
          : addDay(-365, new Date());
      return test;
    }
  },
  mounted() {
    this.formData.followDate = parseDate(new Date(), "-");
    if (localStorage.getItem("userInfo")) {
      this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
      console.log(this.userInfo);
    }
    this.setUserInfo();
    console.log("formData:", this.formData);

    this.detailId = this.$route.query.billId;
    this.customerId = this.$route.query.customerId;
    console.log("detailId:", this.detailId);
    console.log("customerId:", this.customerId);
    // 从客档详情页面进入，需要查询客档信息，从跟进详情进入，则需要查询跟进详情
    if (this.detailId) {
      this.getFollowIdetail();
    } else {
      this.getCustomerDetail();
      this.getLevelList();
    }
    this.getDReasonList();
    this.getDriveEnumList();
    this.getFollowTypeEnumList();
    // this.getLevelList()
  },
  methods: {
    // 是否试驾枚举
    async getDriveEnumList() {
      console.log("试驾枚举");
      this.testDriveList = await this.getEnumList("testDrive");
    },
    // 跟进方式
    async getFollowTypeEnumList() {
      console.log("跟进方式");
      this.followTypeList = await this.getEnumList("customerFollowType");
    },
    // 获取客户级别
    async getLevelList() {
      console.log("获取客户级别");
      this.cusLevelColumns = await this.getEnumList("custLevelEnum");
      this.cusLevelColumns = this.cusLevelColumns.filter(
        e => e.name !== "O" && e.name !== "未定级"
      );
      if (this.detailId) {
        this.currentMaxDate = this.cusLevelColumns.filter(
          e => e.name === this.formData.cusLevel
        )[0].days;
      }
    },
    // 根据key值获取枚举值
    async getEnumList(key) {
      const res = await getEnums({
        key //固定值
      });
      return res.data;
    },
    // 获取D级原因列表
    getDReasonList() {
      console.log("获取D级原因列表");
      secondHandCarFacade({
        method: "getDReason" // 固定值
      }).then(res => {
        this.failReasonColumns = res.data;
      });
    },
    // 根据ID获取跟进详情
    getFollowIdetail() {
      console.log("根据ID获取跟进详情");
      secondHandCarFacade({
        method: "getCustomerFollowById", // 固定值
        billId: this.detailId // 单据ID，必填，String
      }).then(res => {
        this.formData = res.data;
        this.formData.name = this.formData.customerName;
        this.formData.DReasonName = this.formData.DFailRes;
        this.formData.followTypeName = this.formData.followTypeAlias;
        // this.formData.followDate = parseDate(new Date(), '-')
        // this.formData.nextFollowDate = ''
        this.setUserInfo();
        this.getLevelList();
      });
    },
    // 根据客档ID查询客档信息
    getCustomerDetail() {
      console.log("根据客档ID查询客档信息");
      secondHandCarFacade({
        method: "getCustomerById", // 固定值
        billId: this.customerId // 单据ID，必填，String
      }).then(res => {
        this.formData = res.data;
        this.setUserInfo();
        this.formData.followDate = parseDate(new Date(), "-");
      });
    },
    setUserInfo() {
      this.formData.saleEmp = this.userInfo.kdusername;
      this.formData.followPersonId = this.userInfo.kdpersonid;
    },
    // 单项选择
    onPicker(columns, pickerName, pickerId) {
      this.pickerName = pickerName;
      this.pickerId = pickerId;
      this.columns = columns;
      this.showPicker = true;
    },
    // 点击跟进日期时
    onChooseDate(dateStr, type) {
      if (type === 2) {
        if (!this.formData.cusLevelAlias) {
          this.$toast.fail("请先选择意向级别");
          return;
        }
      }
      if (dateStr && dateStr.length > 0) {
        this.defaultDate = new Date(dateStr.replaceAll("-", "/"));
      } else {
        this.defaultDate = new Date();
      }
      this.showCalendar = true;
      this.currentDateChoose = type;
    },
    // 日历确认
    onCalendarConfirm(date) {
      const nowFollowDate = new Date(
        this.formData.followDate.replaceAll("-", "/")
      ).getTime();
      const nextFollowDate = new Date(
        this.formData.nextFollowDate.replaceAll("-", "/")
      ).getTime();
      console.log(nowFollowDate);
      console.log(nextFollowDate);
      if (nowFollowDate > nextFollowDate) {
        this.$toast.fail("跟进日期不能大于下次跟进日期，请重新选择");
        return;
      }
      if (this.currentDateChoose === 1) {
        this.formData.followDate = parseDate(date, "-");
      } else if (this.currentDateChoose === 2) {
        this.formData.nextFollowDate = parseDate(date, "-");
      }
      this.showCalendar = false;
    },
    // 意向级别或D级原因选择确认
    onPickerConfirm(item) {
      console.log("onPickerConfirm:", item);
      this.formData[this.pickerName] = item.name;
      this.formData[this.pickerId] = item.value;
      if (this.pickerName === "DReasonName") {
        // this.formData[this.pickerName] = item[1]
        const pList = this.failReasonColumns.filter(e => e.name === item[0]);
        const pItem = pList[0].children.filter(e => e.name === item[1])[0];
        this.formData[this.pickerId] = pItem.billId;
        this.formData[this.pickerName] = pItem.name;
      }
      // 下次跟进日期的默认值根据选择的客户级别设置
      if (this.pickerName === "cusLevelAlias") {
        this.currentMaxDate = item.days;
        this.formData.nextFollowDate = parseDate(
          addDay(item.days, new Date()),
          "-"
        );
      }
      this.showPicker = false;
    },
    // 提交或保存时
    onSumit(saveOrSubmit) {
      console.log("saveOrSubmit:", saveOrSubmit);
      this.formData.saveOrSubmit = saveOrSubmit;
      this.$refs.form
        .validate()
        .then(res => {
          console.log("res:", res);
          const test = this.formData.testDrive;
          if (!test || test.length < 1) {
            this.$toast.fail("请选择是否试驾");
            return;
          }
          let formData = JSON.parse(JSON.stringify(this.formData));
          console.log("formData:", formData);
          let params = {
            method: "", //固定值
            customerId: "", //客户档案ID，必填
            followType: formData.followType, //跟进类型
            followPersonId: formData.followPersonId, //跟进人员ID，String，必填
            followDate: formData.followDate, //跟进日期，String，必填
            cusLevel: formData.cusLevel, //意向级别,必填，String
            DReasonId: formData.DReasonId || "", //D级原因，String
            DReasonDes: formData.DReasonDes || "", //D级原因说明
            failReason: formData.failReason || "", //战败他品，String
            testDrive: formData.testDrive, //是否试驾,必填，String
            nextFollowDate: formData.nextFollowDate, //下次跟进日期,必填，String
            followNote: formData.followNote, //跟进情况记录，String
            saveOrSubmit: formData.saveOrSubmit //保存或者提交，必填，String
            // orgId: '', //组织ID,必填
            // userId: '', //用户ID，必填，String
          };
          if (this.detailId) {
            params.method = "updateCustomerFollow";
            params.cusViewId = this.detailId;
          } else {
            params.method = "addCustomerFollow";
            params.customerId = this.customerId;
          }

          // delete formData.billId
          // delete formData.brandId
          // delete formData.brandName
          // delete formData.showOrgName
          // delete formData.name
          // delete formData.sourceChannelName
          // delete formData.interModelName
          // delete formData.saleEmp
          // delete formData.sourceChannelName
          // delete formData.DReasonName
          // delete formData.arriveStop
          // delete formData.arriveTimes

          secondHandCarFacade(params).then(res => {
            console.log("根据写入res:", res);
            // 成功返回用户详情
            if (res.code === 1) {
              this.goBack(false);
            } else {
              // TODO 一下一行测试代码
              // this.goBack(false)
              this.loading = false;
              this.$toast.fail(res.msg);
            }
          });
        })
        .catch(err => {
          console.log("valid err:", err);
          this.loading = false;
          this.$toast.fail("请完善信息");
        });
    },
    // 返回客户详情
    goDetail(isBack) {
      this.$router.replace({
        path: "/customManageDetail",
        query: {
          billId: this.customerId || this.formData.customerId,
          tabActive: isBack ? "" : "follow",
          goTwo: true
        }
      });
    },
    // 跳转跟进详情
    goAFollowDetail() {
      // const backlen=history.length-1;
      // history.go(-backlen);
      this.$router.replace({
        path: "/customManageFollowDetail",
        query: { billId: this.detailId }
      });
    },
    // 返回客户详情
    goBack(isBack) {
      if (this.detailId) {
        this.goAFollowDetail();
      } else {
        this.goDetail(isBack);
      }
    }
  }
};
</script>

<style lang="less" scoped>
.follow-edit-ctn {
  background-color: #ffffff;
  min-height: 100vh;
  padding-bottom: 25px;
}
.btn {
  width: 80%;
  background: #1684fc;
  color: #fff;
  font-size: 20px;
  margin: auto;
  border-radius: 20px;
  padding: 10px;
  text-align: center;
  margin-bottom: 25px;
  margin-top: 25px;
}
.saveBtn {
  background: #bbbbbb;
}
.van-radio--horizontal {
  margin: 0 0 0 10px;
}
</style>